package threadPoolTest;

import java.util.concurrent.LinkedBlockingQueue;

public class MyThreadPool {
    private LinkedBlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<>();
    private volatile int coreSize;
    private volatile int maxSize;
    private volatile int nowSize;


    public MyThreadPool(int coreSize, int maxSize) {
        this.coreSize = coreSize;
        this.maxSize = maxSize;
    }

    public void commit(Runnable runnable) {
        if (nowSize < maxSize) {
            synchronized (this) {
                nowSize++;
                new MyThread(runnable).start();
            }
        } else {
            taskQueue.add(runnable);
        }
    }

    class MyThread extends Thread {
        Runnable runnable;

        public MyThread(Runnable runnable) {
            this.runnable = runnable;
        }

        @Override
        public void run() {
            while (true) {
                if (runnable != null) {
                    runnable.run();
                    runnable = null;
                } else {
                    if (nowSize <= coreSize) {
                        try {
                            taskQueue.take().run();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        //销毁
                        synchronized (MyThreadPool.this) {
                            nowSize--;
                        }
                        break;
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        MyThreadPool pool = new MyThreadPool(1, 1);
        pool.commit(() -> {
            System.out.println(Thread.currentThread());
            try {
                Thread.sleep(1000 * 5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        pool.commit(() -> {
            System.out.println(Thread.currentThread());
            try {
                Thread.sleep(1000 * 5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}
